package com.lkd.http.controller;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.wxpay.plus.WXConfig;
import com.github.wxpay.plus.WxPayParam;
import com.github.wxpay.plus.WxPayTemplate;
import com.lkd.common.VMSystem;
import com.lkd.config.ConsulConfig;
import com.lkd.config.LockConfig;
import com.lkd.config.TopicConfig;
import com.lkd.contract.OrderCheck;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.OrderEntity;
import com.lkd.exception.LogicException;
import com.lkd.service.OrderService;
import com.lkd.utils.DistributedLock;
import com.lkd.vo.PayVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WxPayTemplate wxPayTemplate;

    @Autowired
    private MqttProducer mqttProducer;

    @Autowired
    private ConsulConfig consulConfig;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 微信小程序支付
     * @param payVO
     * @return
     */
    @PostMapping("/weixinPay")
    public Map<String, String> weixinPay(@RequestBody PayVO payVO){

        var orderEntity = orderService.createOrder(payVO);//创建订单
        //封装支付请求对象调用支付
        var param=new WxPayParam();
        param.setBody(orderEntity.getSkuName());//商品名称
        param.setOutTradeNo(orderEntity.getOrderNo());// 订单号
        param.setTotalFee(orderEntity.getAmount());//金额
        param.setOpenid(orderEntity.getOpenId());//如果本地支付openid为""
        Map<String, String> map = wxPayTemplate.requestPay(param);

        return map;
    }


    //支付回调方法，当扫描支付成功之后，微信会主动回调接口
    @RequestMapping("/payNotify")
    public void payNotify(HttpServletRequest request, HttpServletResponse response){
        try{
            //1.通过工具类获取支付结果
            Map<String, String> result = wxPayTemplate.validPay(request.getInputStream());
            if(Objects.equals(result.get("code"),"SUCCESS")){
                //支付成功
                //获取订单号
                String orderSn = result.get("order_sn");
                OrderEntity order = orderService.getOne(Wrappers.<OrderEntity>lambdaQuery()
                        .eq(OrderEntity::getOrderNo, orderSn)
                );

                if(!Objects.equals(VMSystem.PAY_STATUS_NOPAY,order.getPayStatus())){
                    //返回微信成功标识，否则会重复调用你的接口
                    response.setContentType("text/xml");
                    response.getWriter().write(WXConfig.RESULT);
                    return;
                }

                order.setThirdNo(result.get("transaction_id")); //交易流水号
                order.setStatus(VMSystem.ORDER_STATUS_PAYED); //修改订单状态已支付
                order.setPayStatus(VMSystem.PAY_STATUS_PAYED); //修改支付状态已支付
                orderService.updateById(order);

                //编写出货流程
                //1.售货机编码  2.商品id
                orderService.vendout(order.getOrderNo(),order.getSkuId(),order.getInnerCode());

                response.setContentType("text/xml");
                response.getWriter().write(WXConfig.RESULT);
            }
        }catch (Exception e){
            log.error("支付回调失败",e);
        }

    }
}
